package com.jiaoyou.baojian.activity;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.jiaoyou.baojian.R;
import com.jiaoyou.baojian.entity.UserTrustInfo;
import com.jiaoyou.baojian.http.Api;
import com.jiaoyou.baojian.http.BaofangCallback;
import com.jiaoyou.baojian.otto.AppBus;
import com.jiaoyou.baojian.otto.Event;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;

public class TixianActivity extends BaseActivity {

    @BindView(R.id.alipay_icon)
    ImageView alipayIcon;
    @BindView(R.id.alipay)
    TextView alipayTxt;
    @BindView(R.id.alipay_layout)
    LinearLayout alipayLayout;
    @BindView(R.id.wepay_icon)
    ImageView wepayIcon;
    @BindView(R.id.wxpay)
    TextView wxpayTxt;
    @BindView(R.id.wepay_layout)
    LinearLayout wepayLayout;
    @BindView(R.id.account)
    EditText account;
    @BindView(R.id.bind)
    Button bind;
    @BindView(R.id.bind_layout)
    LinearLayout bindLayout;
    @BindView(R.id.money)
    EditText money;
    @BindView(R.id.allin)
    Button allin;
    @BindView(R.id.allin_layout)
    LinearLayout allinLayout;
    @BindView(R.id.tixian)
    Button tixian;
    private UserTrustInfo alipay, wxpay;

    private float ketixian;

    private int selected = -1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);

        setTitle("提现");

        alipay = (UserTrustInfo) getIntent().getSerializableExtra("alipay");
        wxpay = (UserTrustInfo) getIntent().getSerializableExtra("wxpay");
        ketixian = getIntent().getFloatExtra("ketixian", 0);

        fillData();
    }

    private void fillData() {
        money.setHint("请输入提现金额，当前最多可提现" + ketixian + "RMB");
        if(alipay == null){
            alipayIcon.setImageResource(R.drawable.icon_alipay_unbounded);
            alipayTxt.setText("绑定支付宝");
        } else {
            alipayIcon.setImageResource(R.drawable.icon_alipay);
            alipayTxt.setText(alipay.getOuterId());
        }
        if(wxpay == null){
            wepayIcon.setImageResource(R.drawable.icon_wechat_unbounded);
            wxpayTxt.setText("绑定微信");
        } else {
            wxpayTxt.setText(wxpay.getNickname());
            Glide.with(TixianActivity.this).load(wxpay.getAvatar())
                    .placeholder(R.drawable.icon_wechat_unbounded).crossFade().into(wepayIcon);
        }

        money.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                refreshTixian();
            }
        });
    }

    @Override
    public int getContentView() {
        return R.layout.activity_tixian;
    }

    @OnClick({R.id.alipay_layout, R.id.wepay_layout, R.id.bind, R.id.allin, R.id.tixian})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.alipay_layout:
                selected = 1;
                alipayLayout.setBackgroundColor(getResources().getColor(android.R.color.white));
                wepayLayout.setBackgroundColor(getResources().getColor(android.R.color.transparent));
                if(alipay == null){
                    bindLayout.setVisibility(View.VISIBLE);
                } else {
                    bindLayout.setVisibility(View.GONE);
                }
                refreshTixian();
                break;
            case R.id.wepay_layout:
                selected = 2;
                wepayLayout.setBackgroundColor(getResources().getColor(android.R.color.white));
                alipayLayout.setBackgroundColor(getResources().getColor(android.R.color.transparent));
                bindLayout.setVisibility(View.GONE);
                if(true){
                    //TODO
                    toast("等待下一版接入");
                    return;
                }
                if(wxpay == null){
                    toast("跳转到绑定微信");
                    bindWx();
                    return;
                }
                refreshTixian();
                break;
            case R.id.bind:
                if(TextUtils.isEmpty(account.getEditableText().toString()))
                    return;
                Api.getInstance().outerAlipay(account.getEditableText().toString(),
                        new BaofangCallback<String>() {
                            @Override
                            public void onFailure(Call call, Throwable t) {

                            }

                            @Override
                            public void onSuccess(String s) {
                                toast("绑定成功");
                                alipayTxt.setText(account.getEditableText().toString());
                                account.setText("");
                                alipay = new UserTrustInfo();
                                alipay.setOuterId(account.getEditableText().toString());
                                alipayLayout.performClick();
                                money.setText("");
                            }
                        });
                break;
            case R.id.allin:
                money.setText("" + ketixian);
                break;
            case R.id.tixian:
                if(selected == 2){
                    toast("微信提现暂不支持，下一版接入");
                    return;
                }
                float m;
                try {
                    m = Float.parseFloat(money.getEditableText().toString());
                } catch (NumberFormatException e){
                    toast("请输入合法的金额");
                    return;
                }
                if(m > ketixian) {
                    toast("输入的太多了，您目前最多可以提现" + ketixian + "元");
                    return;
                }
                String type = null;
                if(selected == 1){
                    type = "alipay";
                } else if(selected == 2){
                    type = "weixin";
                } else {
                    toast("请选择提现渠道");
                    return;
                }
                waiting("申请中....");
                Api.getInstance().withdrawApply(m, type, new BaofangCallback<Double>() {
                    @Override
                    public void onFailure(Call call, Throwable t) {
                        stopWaiting();
                        toast("提现失败：" + t.getLocalizedMessage());
                    }

                    @Override
                    public void onSuccess(Double res) {
                        stopWaiting();
                        toastFullscreen("提现申请成功，财务将在周末统一安排转账，请耐心等待");
                        AppBus.getInstance().post(Event.EVENT_ALIPAY);
                        AppBus.getInstance().post(Event.EVENT_REFRESH_USERINFO);
                        finish();
                    }
                });
                break;
        }
    }

    private void bindWx() {
        UMShareAPI.get(this).getPlatformInfo(this, SHARE_MEDIA.WEIXIN, umAuthListener);
    }

    private UMAuthListener umAuthListener = new UMAuthListener() {
        @Override
        public void onStart(SHARE_MEDIA platform) {
            //授权开始的回调
        }
        @Override
        public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
            toast("授权成功");
            waiting("保存账户信息");
            final String openid = data.get("openid");
            final String name = data.get("name");
            String city = data.get("city");
            String province = data.get("province");
            String country = data.get("country");
            String gender = data.get("gender");
            final String iconurl = data.get("iconurl");
            Api.getInstance().outerWxpay(openid, name, iconurl, gender, province, city,
                    new BaofangCallback<String>() {
                        @Override
                        public void onFailure(Call call, Throwable t) {
                            stopWaiting();
                            toast("绑定失败，请重试");
                        }

                        @Override
                        public void onSuccess(String s) {
                            stopWaiting();
                            toast("绑定成功");
                            wxpayTxt.setText(name);
                            Glide.with(TixianActivity.this).load(iconurl)
                                    .placeholder(R.drawable.icon_wechat_unbounded).crossFade().into(wepayIcon);
                            wxpay = new UserTrustInfo();
                            wxpay.setOuterId(openid);
                            AppBus.getInstance().post(Event.EVENT_WALLET_BIND_SUCCESS);
                            money.setText("");
                            refreshTixian();
                        }
                    });
        }

        @Override
        public void onError(SHARE_MEDIA platform, int action, Throwable t) {
            toast("授权失败");
        }

        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
            toast("取消");
        }
    };

    private void refreshTixian(){
        if(selected == -1) {
            tixian.setEnabled(false);
            return;
        }
        if(selected == 1 && alipay == null){
            tixian.setEnabled(false);
            return;
        }
        if(selected == 2 && wxpay == null){
            tixian.setEnabled(false);
            return;
        }
        if(TextUtils.isEmpty(money.getEditableText().toString())){
            tixian.setEnabled(false);
            return;
        }
        tixian.setEnabled(true);
    }
}
